package com.gzl.gg.thread;

import java.util.Random;

/**
 * Created by Administrator on 2018/10/30.
 */
public class MyThread {


    static int xue = 20;
    public static void main(String [] args){

        final Integer lock = new Integer(0);//定义一个对象
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {//定义 A 线程
                boolean flag = true;
                while (flag) {
                    try {
                        synchronized(lock){
                            if ( xue < 0 ){
                                System.out.println(" is die ");
                                flag = false;
                            }else{
                                int num = (int)(Math.random()*20+1);
                                xue = xue - num;
                                System.out.println("失血 " + num + "，剩下 " + xue);
                                Thread.sleep(1000);
                                lock.notify();//notify不会释放锁，只会通知其他线程进入就绪状态
                                lock.wait();//wait会释放锁, 进入 等待状态
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public  void run() {//定义 B 线程
                boolean flag = true;
                while (true) {
                    try {
                        synchronized(lock){
                            if ( xue < 0 ){
                                System.out.println(" is die ");
                                flag = false;
                            }else{
                                int num = (int)(Math.random()*20+1);
                                xue = xue + num;
                                System.out.println("补血 " + num + "，还有 " + xue);
                                Thread.sleep(1000);
                                lock.notify();
                                lock.wait();
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t1.start();//启动 A 线程
        t2.start();//启动 B 线程
        try {
            t2.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
